package com.cao.utils;

import com.cao.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: huahua
 * @Date: 2021-04-13 21:31
 */
@Component
public class HtmlParseUtils {
    public static void main(String[] args) throws IOException {
        HtmlParseUtils utils = new HtmlParseUtils();
        utils.JDParse("茅台").forEach(System.out::println);
    }

    public List<Content> JDParse(String keyword) throws IOException {

        ArrayList<Content> contentList = new ArrayList<>();

        String url = "https://search.jd.com/Search?keyword="+keyword+"&enc=utf-8";

        Document document = Jsoup.parse(new URL(url), 30000);

        Element element = document.getElementById("J_goodsList");

        Elements elements = element.getElementsByTag("li");

        for (Element el : elements) {
            //得到图片
            Content content = new Content();

            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);

            contentList.add(content);
        }

        return contentList;
    }
}
